package com.beasts.antpage.core.common.token;

import com.beasts.antpage.core.utils.HttpClientUtil;
import com.beasts.antpage.core.utils.encrypt.Base64Util;
import com.beasts.antpage.core.utils.json.JacksonUtil;
import com.beasts.antpage.core.utils.json.JsonUtil;
import com.beasts.antpage.core.utils.servlet.CookieUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * ant-uc（react） oauth token
 *
 * @author Locker
 * @date 31/05/2018 5:30 PM
 * @since 1.0
 */
public class AntUCToken {

    private AntUCToken() {
    }

//    private ThreadLocal threadLocal = new ThreadLocal();

    //    @Value("${token.antuc.url}")
    private static String tokenUrl;

    //    @Value("${token.antuc.clientId}")
    private static String clientId;

    //    @Value("${token.antuc.clientSecret}")
    private static String clientSecret;

    //    @Value("${token.antuc.scope}")
    private static String scope;

    //    @Value("${token.antuc.grantType}")
    private static String grantType;

    // 获取token
    private static final String TOKEN_GET_MAPPING = "/oauth/token";
    // 获取用户信息
    public static final String TOKEN_USERINFO_MAPPING = "/authentication/userInfo";
    // 移除token
    public static final String TOKEN_REMOVE_MAPPING = "/authentication/removeToken";
    // token请求的header.key
    private static final String TOKEN_HEADER = "Authorization";
    // 获取token的header.Authorization值
    private static final String TOKEN_USERINFO_HEADER_VALUE_PRE = "bearer ";
    private static final String TOKEN_GET_HEADER_VALUE_PRE = "basic ";
    private static String TOKEN_GET_HEADER_VALUE;

    static {
//        tokenUrl = "http://127.0.0.1:4444";
        tokenUrl = "http://118.31.11.42";
        clientId = "client_ant_page";
        clientSecret = "client_ant_page_secret";
        scope = "select";
        grantType = "password";
        TOKEN_GET_HEADER_VALUE = TOKEN_GET_HEADER_VALUE_PRE + Base64Util.encode(clientId + ":" + clientSecret);
    }

    /**
     * 获取 oauth token 基础 url
     *
     * @return
     */
    private static StringBuilder baseTokenUrl(String mapping) {
        StringBuilder url = new StringBuilder();
        url.append(tokenUrl)
                .append(mapping)
                .append("?")
                .append("client_id=" + clientId + "&")
                .append("client_secret=" + clientSecret + "&")
                .append("scope=" + scope + "&")
                .append("grant_type=" + grantType + "&");
        return url;
    }

    private static String fullGetTokenUrl(String username, String password) {
        return baseTokenUrl(TOKEN_GET_MAPPING).append("username=" + username + "&")
                .append("password=" + password).toString();
    }

    /**
     * 获取服务器端 token
     *
     * @param username
     * @param password
     * @return
     */
    public static String getToken(String username, String password) {
        String result;
        try {
            result = HttpClientUtil.sendPostDataByMap(fullGetTokenUrl(username, password), null, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return result;
    }

    public static String getTokenProperty(String username, String password, String keyName) {
        String result = getToken(username, password);
        try {
            Map<String, String> map = JsonUtil.string2Obj(result, Map.class);
            return map.get(keyName);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 从请求中获取 cookie
     *
     * @param req
     * @return
     */
    public static String getTokenFromRequest(HttpServletRequest req) {
        Cookie token = CookieUtil.getCookieByName(req, "token");
        return token.toString();
    }


    /**
     * 获取 token-user
     *
     * @param token
     * @return
     */
    public static Map<String, Object> getUserByToken(String token) {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put(TOKEN_HEADER, TOKEN_USERINFO_HEADER_VALUE_PRE + token);
        String res;
        try {
            res = HttpClientUtil.sendPostDataByMap(tokenUrl + TOKEN_USERINFO_MAPPING, null, "UTF-8", headerMap);
            if (null == res) {
                return null;
            }
            return JacksonUtil.json2map(res);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 移除 token
     * TODO removeToken() 转接 ant-auth 返回值
     *
     * @param token
     * @return
     */
    public static boolean removeToken(String token) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("access_token", token);
        Object obj;
        try {
            obj = HttpClientUtil.sendPostDataByMap(tokenUrl + TOKEN_REMOVE_MAPPING, paramMap, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    // TODO wait 本地存储 Thread token-user，当前为 ant-auth
//    public static boolean localSave(String token) {
//        return false;
//    }

}
